package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;


import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.LiveListFirstPageAdapter;
import com.xgkj.diyiketang.activity.data.MyZhiboAdapter;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.DeleteZhiboTask;
import com.xgkj.diyiketang.task.LiveListTask;
import com.xgkj.diyiketang.util.NoDataUtil;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.weidget.PullToRefreshListView;
import com.xgkj.diyiketang.yizhibo.Constants;
import com.xgkj.diyiketang.yizhibo.PlayerNewActivity;
import com.xgkj.diyiketang.yizhibo.Preferences;

import java.util.ArrayList;
import java.util.List;

public class MyZhiboListActivity extends BaseActivity implements PullToRefreshListView.OnRefreshListener, PullToRefreshListView.OnLoadDataListener, LiveListFirstPageAdapter.OnAdapterClickListener {
    private Context mContext;
    private PullToRefreshListView mListView;
    //    private MyZhiboAdapter mAdapter;
    private LiveListFirstPageAdapter mAdapter;
    private int currentPage = 1;
    private int size = 20;
    private int myzhiboListTaskId = -1;
    private String mUserId;
    private int deleteZhiboTaskId = -1;
    private NoDataUtil noDataUtil;
    private String versionCode;
    private String isPlayer;
    private int s = 0;
    private String type;
    private int myFirstzhiboListTaskId = -1;
    private List<EatShowUserInfo> list = new ArrayList<>();
    //    private YZBSdk mYZBSdk;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_zhibo_list);
        mContext = this;
        initView();
        checkAppKey(Constants.APP_KEY_ID);
//        mYZBSdk = YZBSdkFactory.getInstance().getYZBSdkInstance(mContext, Constants.APP_KEY_ID);
//        mYZBSdk.registerApp(Constants.APP_KEY_ID, Constants.APP_KEY_SECRET);
    }

    private void checkAppKey(String appkey) {
        String cachedAppKey = Preferences.getInstance(mContext.getApplicationContext()).getString(Preferences.KEY_APP_KEY);
        if (TextUtils.isEmpty(cachedAppKey) || !cachedAppKey.equals(appkey)) {
            Preferences.getInstance(mContext.getApplicationContext()).putString(Preferences.KEY_APP_KEY, appkey);
            Preferences.getInstance(mContext.getApplicationContext()).remove(Preferences.KEY_SESSION_ID);
            Preferences.getInstance(mContext.getApplicationContext()).remove(Preferences.KEY_USER_NUMBER);
            Preferences.getInstance(mContext.getApplicationContext()).remove(Preferences.KEY_USER_NICKNAME);
        }
    }

    private void initView() {
        try {
            PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            versionCode = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Intent intent = getIntent();
        if (intent.getStringExtra("type")!=null){
            type = intent.getStringExtra("type");
            list.clear();
        }
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        View view = findViewById(R.id.content_layout);
        noDataUtil = new NoDataUtil(mContext, view);
        mListView = (PullToRefreshListView) findViewById(R.id.zhibo_list);
        mListView.init(mContext, true);
        mAdapter = new LiveListFirstPageAdapter(mContext);
        mAdapter.setOnAdapterClickListener(this);
        mListView.setAdapter(mAdapter, true);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mListView.getHeaderViewsCount() > 0) {
                    position--;
                }
                if (position < 0 || position >= mAdapter.getCount()) return;
                EatShowUserInfo info = (EatShowUserInfo) mAdapter.getItem(position);
                String vid = info.getVid();
                if (!TextUtils.isEmpty(info.getIsMoive2())) {
                    isPlayer = info.getIsMoive2();
                }

                Intent intent = new Intent(mContext, PlayerNewActivity.class);
                intent.putExtra(Constants.EXTRA_KEY_VIDEO_ID, vid);
                intent.putExtra("ZHIBO_LIST", mAdapter.getDataList());
                intent.putExtra("CURRENT_POSITION", position);
                intent.putExtra(Constants.ZHIBO_PLAY, isPlayer);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        mListView.setOnRefreshListener(this);
        mListView.setOnLoadDataListener(this);
        mUserId = getEatShowApp().getmUserInfo().getUserId();
        mListView.doRefresh();
    }

    private void getZhiboList() {
        if (currentPage == 0) {
            mListView.setNoNextPage();
            return;
        }
//        LiveListTask liveListTask = new LiveListTask(size, currentPage, null, mUserId, 4, versionCode, null, null, null, "0","1","1");
        LiveListTask task = new LiveListTask(size, currentPage, null, null, 4, versionCode, "", "", "", "", "0", "1");
        task.addListener(new TaskEventListener(mContext));
        myzhiboListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }
    private void getFirstZhiboList() {
        if (currentPage == 0) {
            mListView.setNoNextPage();
            return;
        }
//        LiveListTask liveListTask = new LiveListTask(size, currentPage, null, mUserId, 4, versionCode, null, null, null, "0","1","1");
        LiveListTask task = new LiveListTask(size, currentPage, null, null, 4, versionCode, "", "", "", "", "2", "1");
        task.addListener(new TaskEventListener(mContext));
        myFirstzhiboListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    class TaskEventListener extends ShowToastTaskEventListener {
        public TaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);

            if (myzhiboListTaskId == taskId) {
                if (data != null) {
                    list = (List<EatShowUserInfo>) data;
                    Log.e("data", "handleTaskCompleted: " + list.toString());
                    if (currentPage == 1) {
                        mListView.onRefreshComplete();
                        mListView.enableLoadMore();
                        mAdapter.clearData();
                    } else {
                        mListView.onLoadDataComplete(true);
                    }

                    if (list.size() > 0) {
                        mAdapter.updateData(list, s);
                        Log.e("data", "handleTaskCompleted:" + list.toString());
                        if (currentPage == 1) {
                            mListView.post(new Runnable() {
                                @Override
                                public void run() {
                                    mListView.scrollTo(0, 10);
                                }
                            });
                        }
                    }
                    currentPage = result;
                } else {
                    mAdapter.clearData();
                    mListView.onRefreshComplete();
                    noDataUtil.ListViewEmpty(mListView, null, null, -1);
                }
                if (mAdapter != null && mAdapter.getCount() > 0) {
                    noDataUtil.ListViewNoEmpty(mListView);
                } else {
                    noDataUtil.ListViewEmpty(mListView, null, null, -1);
                }
            } else if (deleteZhiboTaskId == taskId) {
                mListView.doRefresh();
            }else if (myFirstzhiboListTaskId == taskId) {
                if (data != null) {
                    list = (List<EatShowUserInfo>) data;
                    Log.e("data", "handleTaskCompleted: " + list.toString());
                    if (currentPage == 1) {
                        mListView.onRefreshComplete();
                        mListView.enableLoadMore();
                        mAdapter.clearData();
                    } else {
                        mListView.onLoadDataComplete(true);
                    }
                    if (list.size() > 0) {
                        mAdapter.updateData(list, 3);
                        Log.e("data", "handleTaskCompleted:" + list.toString());
                        if (currentPage == 1) {
                            mListView.post(new Runnable() {
                                @Override
                                public void run() {
                                    mListView.scrollTo(0, 10);
                                }
                            });
                        }
                    }
                    currentPage = result;
                } else {
                    mAdapter.clearData();
                    mListView.onRefreshComplete();
                    noDataUtil.ListViewEmpty(mListView, null, null, -1);
                }
                if (mAdapter != null && mAdapter.getCount() > 0) {
                    noDataUtil.ListViewNoEmpty(mListView);
                } else {
                    noDataUtil.ListViewEmpty(mListView, null, null, -1);
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (myzhiboListTaskId == taskId) {
                if (currentPage == 1) {
                    mListView.onRefreshComplete();
                } else {
                    mListView.onLoadDataComplete(false);
                }
            }
        }
    }

    ;


    @Override
    public void onPullRefresh() {

    }

    @Override
    public void onLoadMore() {
        if (type.equals("my_zhibo")){
            getZhiboList();
        }else {
            getFirstZhiboList();
        }

    }

    @Override
    public void onRefresh() {
        currentPage = 1;
        if (type.equals("my_zhibo")){
            getZhiboList();
        }else {
            getFirstZhiboList();
        }
    }

    //
    @Override
    public void onItemLongClick(EatShowUserInfo info) {
        DeleteZhiboTask deleteZhiboTask = new DeleteZhiboTask(info.getVid());
        deleteZhiboTask.addListener(new TaskEventListener(mContext));
        deleteZhiboTaskId = getEatShowApp().getTaskManager().addTask(deleteZhiboTask);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!TextUtils.isEmpty(EatShowApp.getACache().getAsString(Constants.USE_GUANKANQUAN))) {
            String isUse = EatShowApp.getACache().getAsString(Constants.USE_GUANKANQUAN);
            if (isUse.equals("true")) {
                if (type.equals("my_zhibo")){
                    getZhiboList();
                }else {
                    getFirstZhiboList();
                }
            }
        }
    }
}
